<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <script src="/js/jquery-1.12.3.min.js"></script>
    <link rel="stylesheet" href="/bootstrap/bootstrap.min.css">
    <script src="/bootstrap/bootstrap.min.js"></script>
    <style>
        body{
            margin-top:5px;
            background: url('static/img/chat-bg.jpg') no-repeat center center fixed;
            background-size: 100%;
        }
    </style>
</head>
<body>
<input type="hidden" name="uid" th:value="${session.uid}" value="" id="uid">
<input type="hidden" name="username" th:value="${session.username}" value="" id="uname">
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">当前登录用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group">
                        <a href="#" class="list-group-item">你好，<span th:text="${session.username}"></span></a>
                        <a href="logout" class="list-group-item list-group-item-danger">退出</a>
                    </div>
                </div>
            </div>
            <div class="panel panel-primary" id="online">
                <div class="panel-heading">
                    <h3 class="panel-title">当前在线的其他用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group" id="users">
                    </div>
                </div>
            </div>
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">群发系统广播</h3>
                </div>
                <div class="panel-body">
                    <input type="text" class="form-control"  id="msg" /><br>
                    <button id="broadcast" type="button" class="btn btn-primary">发送</button>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title" id="talktitle"></h3>
                </div>
                <div class="panel-body">
                    <div class="well" id="log-container" style="height:400px;overflow-y:scroll">

                    </div>
                    <input type="text" id="myinfo" class="form-control col-md-12" /> <br>
                    <button id="send" type="button" class="btn btn-primary">发送</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:inline="none">
    $(document).ready(function() {
        // 指定websocket路径
        const uid = $('#uid').val();
        const username = $('#uname').val();
        const _url = "ws://localhost:8081/ws?uid="+uid;
        const _url2 = "http://localhost:8081/ws/sockjs?"+uid;
        var websocket;
        if ('WebSocket' in window) {
            websocket = new WebSocket(_url);
        } else if ('MozWebSocket' in window) {
            websocket = new MozWebSocket(_url);
        } else {
            websocket = new SockJS(_url2);
        }
        //var websocket = new WebSocket('ws://localhost:8081/Spring-websocket/ws');
        websocket.onmessage = function(event) {
            var data=JSON.parse(event.data);
            if(data.from>0||data.from==-1){//用户或者群消息
                // 接收服务端的实时消息并添加到HTML页面中
                $("#log-container").append("<div class='bg-info'><label class='text-danger'>"+data.fromName+"&nbsp;"+data.date+"</label><div class='text-success'>"+data.text+"</div></div><br>");
                // 滚动条滚动到最低部
                scrollToBottom();
            }else if(data.from==0){//上线消息
                if(data.text!=username)
                {
                    $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data.text+'</a>');
                    alert(data.text+"上线了");
                }
            }else if(data.from==-2){//下线消息
                if(data.text!=username)
                {
                    $("#users > a").remove(":contains('"+data.text+"')");
                    alert(data.text+"下线了");
                }
            }
        };
        $.post("onlineusers",function(data){
            for(var i=0;i<data.length;i++)
                $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data[i]+'</a>');
        });

        $("#broadcast").click(function(){
            $.post("broadcast",{"text":$("#msg").val()});
        });

        $("#send").click(function(){
            const _to = $("body").data("to");
            if (!_to) {
                alert('请选择一个用户进行聊天');
                return;
            }
            $.post("/getuid",{"username":$("body").data("to")},function(d){
                var v=$("#myinfo").val();

                if(v==""){
                    return;
                }else{
                    var data={};
                    data["from"]=uid;
                    data["fromName"]=username;
                    data["to"]=d.uid;
                    data["text"]=v;
                    websocket.send(JSON.stringify(data));
                    $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;"+formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')+"</label><div class='text-info'>"+v+"</div></div><br>");
                    scrollToBottom();
                    $("#myinfo").val("");
                }
            });

        });

    });

    function talk(a){
        $("#talktitle").text("与"+a.innerHTML+"的聊天");
        $("body").data("to",a.innerHTML);
    }
    function scrollToBottom(){
        var div = document.getElementById('log-container');
        div.scrollTop = div.scrollHeight;
    }
    /**
     * Date日期格式化
     * @param date
     * @param pattern 可为空，默认yyyy-MM-dd HH:mm:ss
     * @returns {string}
     */
    function formatDate(date, pattern) {
        let yy = date.getFullYear();      //年
        let mm = date.getMonth() + 1;     //月
        let dd = date.getDate();          //日
        let hh = date.getHours();         //时
        let ii = date.getMinutes();       //分
        let ss = date.getSeconds();       //秒

        let clock = yy + "-";
        if (mm < 10) clock += "0";
        clock += mm + "-";
        if (dd < 10) clock += "0";
        clock += dd + " ";
        if (hh < 10) clock += "0";
        clock += hh + ":";
        if (ii < 10) clock += '0';
        clock += ii + ":";
        if (ss < 10) clock += '0';
        clock += ss;
        if (isNull(pattern) || pattern == format_str.yyyy_MM_dd_HH_mm_ss) {
            return clock;
        } else if (pattern == format_str.yyyy_MM_dd) {
            return clock.substring(0, 10);
        } else if (pattern == format_str.HH_mm_ss) {
            return clock.substring(11);
        } else if (pattern == format_str.yyyy_MM_dd_1) {
            return clock.substring(0, 10).replace(/-/g, '/');
        } else if (pattern == format_str.yyyyMMdd) {
            return clock.substring(0, 10).replace(/-/g, '');
        } else {
            return clock;
        }
    }
    /**
     * 判断数据是否为空
     * @param data
     * @returns {boolean}
     */
     function isNull(data) {
        if (data == null || data == undefined || data == '') {
            return true;
        } else {
            return false;
        }
    }
    const format_str = {
        yyyy_MM_dd_HH_mm_ss: "yyyy-MM-dd HH:mm:ss",
        yyyy_MM_dd: "yyyy-MM-dd",
        yyyy_MM_dd_1: "yyyy/MM/dd",
        yyyyMMdd: "yyyyMMdd",
        HH_mm_ss: "HH:mm:ss",
    }
</script>
</body>
</html>